package cn.java86.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;

/**
 * @author oldliu
 * @since 1.0
 */
public class MybatisUtil {
    private static SqlSessionFactory sf;

    private MybatisUtil() {

    }

    static {//静态代码块，执行一次
        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader("mybatis-config.xml");
            sf = new SqlSessionFactoryBuilder().build(reader);
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static SqlSession get() {
        SqlSession sqlSession = sf.openSession();
        return sqlSession;
    }

    public static SqlSession get(boolean autoCommit) {
        SqlSession sqlSession = sf.openSession(autoCommit);
        return sqlSession;
    }

    public static void close(SqlSession s) {
        if (s != null)
            s.close();
    }
}
